package com.lzf.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzf.domain.dto.ErrorCode;
import com.lzf.domain.dto.ReturnValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Oauth2异常信息返回处理
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();

        if(e instanceof BadCredentialsException){
            //如果是client_id和client_secret相关异常 返回自定义的数据格式
            writer.write(mapper.writeValueAsString(new ReturnValue<String>(ErrorCode.ERROR_NO_RIGHT)));
        }else if(e instanceof InsufficientAuthenticationException){
            //如果是没有携带token
            writer.write(mapper.writeValueAsString(new ReturnValue<String>(ErrorCode.ERROR_USER_TOKEN_ERROR)));
        }else {
            writer.write(mapper.writeValueAsString(new ReturnValue<String>(ErrorCode.ERROR_USER_TOKEN_ERROR)));
        }
        writer.flush();
        writer.close();
    }
}

